<?php
namespace Tiger\Component;

class Redis
{
	/**
	 * redis
	 */
	protected $_redis;
	
	public $config;
	
	public static $prefix = "";
	
	public function __construct($config)
	{
		$this->config = $config;
		$this->connect();
	}
	
	protected function connect()
	{
		try 
		{
			if ($this->_redis)
				unset($this->_redis);
			
			$this->_redis = new \Redis();
			if ($this->config['pconnect'])
			{
				$this->_redis->pconnect($this->config['host'], $this->config['port'], $this->config['timeout']);
			}
			else
			{
				$this->_redis->connect($this->config['host'], $this->config['port'], $this->config['timeout']);
			}
			if (!empty($this->config['password']))
			{
				$this->_redis->auth($this->config['password']);
			}
			if (!empty($this->config['database']))
			{
				$this->_redis->select($this->config['database']);
			}
		}
		catch (\Exception $e)
		{
			throw new \Exception('Redis connect false:'.$e->getCode());
		}
	}
	
	public function __call($method, $args = array())
	{
		$reConnect = false;
		while (1)
		{
			try
			{
				$result = call_user_func_array(array($this->_redis, $method), $args);
			}
			catch (\RedisException $e)
			{
				//已重连过，仍然报错
				if ($reConnect)
					throw $e;
		
				if ($this->_redis->isConnected())
					$this->_redis->close();

				$this->connect();
				$reConnect = true;
				continue;
			}
			return $result;
		}
	}
}